from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from django.contrib.auth.models import Permission, Group

from users.models import User


class PermissionModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id', 'name', 'codename', 'content_type')


class ContentTypeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        fields = ('id', 'name')


class GroupModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name', 'permissions')


class AdminModelSerializer(serializers.ModelSerializer):
    """管理员用户序列化器类"""
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'email', 'mobile', 'user_permissions', 'groups')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'allow_blank': True,
                'required': False
            }
        }

    def create(self, validated_data):
        validated_data['is_staff'] = True
        instance = super().create(validated_data)
        password = validated_data.get('password')
        if not password:
            password = '123abc'
        instance.set_password(password)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        password = validated_data.pop('password', '')
        instance = super().update(instance, validated_data)
        if password:
            instance.set_password(password)
            instance.save()
        return instance
